package com.losdun.framework.security.handle;

import com.losdun.common.constant.Constants;
import com.losdun.common.core.domain.model.LoginUser;
import com.losdun.common.utils.MessageUtils;
import com.losdun.common.utils.StringUtils;
import com.losdun.framework.manager.AsyncManager;
import com.losdun.framework.manager.factory.AsyncFactory;
import com.losdun.framework.web.service.TokenService;
import com.losdun.weixin.security.vo.WxLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/29
 * 登出操作实现
 **/
@Configuration
public class LogoutHandlerImpl implements LogoutHandler {
    @Autowired
    private TokenService tokenService;
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

        System.out.println("excute logoutHandler");
        if (request.getRequestURI().equals("/logout")) {
            LoginUser loginUser = tokenService.getLoginUser(request);
            System.out.println("excute admin logoutHandler");
            if (StringUtils.isNotNull(loginUser)) {
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
            }
        }else if (request.getRequestURI().equals("/app/logout")) {
            System.out.println("excute weixin logoutHandler");
            WxLoginUser loginUser = tokenService.getWxLoginUser(request);
            if (StringUtils.isNotNull(loginUser))
            {
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
            }
        }
        System.out.println("excute logoutHandler success!");
    }
}
